##############################################################################################
### Replication material for "Contextualizing Individual Attitudes on Economic Statecraft" ###
##############################################################################################

# Please contact Timothy M. Peterson with any questions or comments: timothy.m.peterson@asu.edu

# Directions: to replicate all main results, just run this entire script file 
## Note: some appendix material is currently commented out

# Clear R environment
rm(list = ls()) 

# Set working directory
setwd(this.path::here(..=0))

# Create output directory
dir.create(path = "Output")


library(tidyverse)
library(haven)
library(survey)
library(sjPlot)
library(sjmisc)
library(ggplot2)
library(ggthemes)
library(grid)
library(Matrix)
library(survival)
library(cregg)
library(survey)
library(gridExtra)
library(ggsci)
library(ggpubr)
library(gtsummary)

# Pulls in data from each of three experiments
source("Code/exp1_coding.R")
source("Code/exp2_coding.R")
source("Code/exp3_coding.R")

# Identify three experiments
exp1$experiment_no <- 1
exp2$experiment_no <- 2
exp3$experiment_no <- 3


# Combine data
combo <- data.frame(rbind(exp1, exp2, exp3))


# Data wrangling
combo <- combo %>%
  mutate(status_quo_long = ifelse(Background == "LongHistory" & Inaction == "Continue", 1, 0),
         back_impact_long = ifelse(Background == "LongHistory" & Rationale == "LongRun", 1, 0),
         status_quo_short = ifelse(Background == "RecentShift" & Inaction == "TickingClock", 1, 0),
         back_impact_short = ifelse(Background == "RecentShift" & Rationale == "Immediate", 1, 0),
         )

combo$badbehavior1 <- factor(combo$badbehavior1)
combo$badbehavior1 <- relevel(combo$badbehavior1, ref = "stopdemocracy")

combo$Author <- factor(combo$Author)
combo$Author <- relevel(combo$Author, ref = "Professional_expert")

combo$AuthorComb <- ifelse(combo$Author == "Professional_expert" |
                             combo$Author == "Professional", 1, 0)


combo$party3 <- ifelse(combo$party == "IndDem" | combo$party == "StrongDem" |
                         combo$party == "WeakDem", "Democrat", 
                ifelse(combo$party == "IndRep" | combo$party == "StrongRep" |
                                combo$party == "WeakRep", "Republican", "Independent/Other"))

combo$party3[is.na(combo$party)] <- "Independent/Other"


combo$EffectOrd <- ifelse(combo$Effect>=50 & combo$Effect<=200, "$50-200 million",
                   ifelse(combo$Effect>200 & combo$Effect<=400, "$201-400 million",       
                  ifelse(combo$Effect>400 & combo$Effect<=600, "$401-600 million", 
                  ifelse(combo$Effect>600 & combo$Effect<=900, "$601-900 million", 0))))        
                         
combo$Policy <- factor(combo$Policy)   
combo$Rationale <- factor(combo$Rationale)   
combo$Background <- factor(combo$Background)   
combo$Inaction <- factor(combo$Inaction)   
combo$Prior <- factor(combo$Prior)   
combo$EffectOrd <- factor(combo$EffectOrd)  
combo$party <- factor(combo$party)  
combo$party3 <- factor(combo$party3)  
combo$country1 <- factor(combo$country1)  

combo$EffectOrd <- relevel(combo$EffectOrd, ref = "$50-200 million")

combo$AuthorComb <- factor(combo$AuthorComb,
                           levels = c(0, 1),
                           labels = c("Appointee", "Professional"))

combo$party3 <- relevel(combo$party3, ref = "Democrat")

combo$Prior <- factor(combo$Prior, levels=c( 'Neutral', 'Very unfavorable', 'Somewhat unfavorable', 'Somewhat favorable', 'Very favorable'))

combo$Author <- factor(combo$Author, levels=c('Professional_expert', 'Professional', 'Appointee_only', 'Appointee_donor'))

combo <- combo %>%
  mutate(Prior3= ifelse(Prior == "Very unfavorable" | Prior == "Somewhat unfavorable", "Unfavorable",
                        ifelse(Prior == "Somewhat favorable" | Prior == "Very favorable", "Favorable",
                               ifelse(Prior == "Neutral", "Neutral", NA))),
         Prior3 = fct_relevel(Prior3,c("Neutral", "Unfavorable", "Favorable")))



###################
### Main models ###
###################

# H1, H4-H6 - constrained design
model_add_full <- DV_support ~ Policy + Background + badbehavior1*country1 + Inaction + Author + Rationale + EffectOrd + Prior3

amces_add_full <- cj(combo, model_add_full,
            id = ~1, alpha=0.05, estimate = "amce")

amces_add_full <- amces_add_full %>%
  mutate(feature = recode(feature, "badbehavior1" = "Issue", "Inaction" = "If no action", 
                          "EffectOrd" = "Effect on target economy", "country1" = "Country",
                          "Policy" = "Proposed policy", "Prior3" = "Prior attitude"),
         level = recode(level, "terror" = "Terror", "drugs" = "Drugs", 
                        "developnukes" = "WMD", "stopdemocracy" = "Democracy crackdown",
                        "TickingClock" = "Ticking clock", "Continue" = "Continuation",
                        "Appointee_only" = "Appointee", "Appointee_donor" = "Appointee donor",
                        "Professional_expert" = "Professional expert"))

full_a <- plot(rbind(amces_add_full)) + scale_colour_viridis_d( begin = 0, end = .7) +
  labs(x="Average marginal component effects")+ theme(legend.position="none")

# ggsave("Output/Rplot_additive_full.pdf", 
#       width = 5.5, height = 7, dpi = 300, units = "in", device='pdf')


amces_add_base <- amces_add_full %>%
  filter(feature != "Country" & feature != "Rationale" & feature != "Effect on target economy" & feature != "Prior attitude")

base_a <- plot(amces_add_base) + scale_colour_viridis_d( begin = 0, end = .7) +
  labs(x="Average marginal component effects") + theme(legend.position="none", axis.title = element_text(size = 8))

# ggsave("Output/Rplot_additive_base.pdf", 
#        width = 5.5, height = 4, dpi = 300, units = "in", device='pdf')


mms_add_full <- cj(combo, model_add_full,
                   id = ~1, alpha=0.05, estimate = "mm")

mms_add_full <- mms_add_full %>%
  mutate(feature = recode(feature, "badbehavior1" = "Issue", "Inaction" = "If no action", 
                          "EffectOrd" = "Effect on target economy", "country1" = "Country",
                          "Policy" = "Proposed policy", "Prior3" = "Prior attitude"),
         level = recode(level, "terror" = "Terror", "drugs" = "Drugs", 
                        "developnukes" = "WMD", "stopdemocracy" = "Democracy crackdown",
                        "TickingClock" = "Ticking clock", "Continue" = "Continuation",
                        "Appointee_only" = "Appointee", "Appointee_donor" = "Appointee donor",
                        "Professional_expert" = "Professional expert"))

full_m <- plot(rbind(mms_add_full)) + scale_colour_viridis_d( begin = 0, end = .7) +
  labs(x="Marginal means")+ theme(legend.position="none")

# ggsave("Output/Rplot_mm_additive_full.pdf",
#        width = 4.5, height = 6, dpi = 300, units = "in", device='pdf')


ggarrange(full_a, full_m, ncol = 2)

ggsave("Output/F3_appendix_full_version.pdf", # in appendix
       width = 10, height = 6, dpi = 300, units = "in", device='pdf')


mms_add_base <- mms_add_full %>%
  filter(feature != "Country" & feature != "Rationale" & feature != "Effect on target economy" & feature != "Prior attitude")

base_m <- plot(mms_add_base) + scale_colour_viridis_d( begin = 0, end = .7) +
  labs(x="Marginal means") + theme(legend.position="none", axis.title = element_text(size = 8))

# ggsave("Output/Rplot_mm_additive_base.pdf",
#       width = 5.5, height = 4, dpi = 300, units = "in", device='pdf')

ggarrange(base_a, base_m, ncol = 2)

ggsave("Output/Figure3.pdf", # paper Figure 3
       width = 7, height = 4, dpi = 300, units = "in", device='pdf')
  

#H3 and H6 (plus others subset as well) AMCEs - constrained design
model_bypol_full <- DV_support ~ Background + Prior3 + badbehavior1 * country1 + Inaction + Author + Rationale + EffectOrd

amces_bypol_full <- cj(combo, model_bypol_full, 
                       id = ~1, alpha=0.05, estimate = "amce", by = ~ Policy)

amces_bypol_full <- amces_bypol_full %>%
  mutate(feature = recode(feature, "badbehavior1" = "Issue", "Inaction" = "If no action", "Prior3" = "Prior attitude", 
                          "EffectOrd" = "Effect on target economy", "country1" = "Country"),
         level = recode(level, "terror" = "Terror", "drugs" = "Drugs", 
                        "developnukes" = "WMD", "stopdemocracy" = "Democracy crackdown",
                        "TickingClock" = "Ticking clock", "Continue" = "Continuation",
                        "Appointee_only" = "Appointee", "Appointee_donor" = "Appointee donor",
                        "Professional_expert" = "Professional expert"))

plot(rbind(amces_bypol_full)) + ggplot2::facet_wrap(~BY, ncol = 4L) + scale_color_jco() +
  labs(x="Average marginal component effects") + theme(legend.position="none")

ggsave("Output/F4_appendix_full_version.pdf", # in appendix
       width = 6.5, height = 6, dpi = 300, units = "in", device='pdf')


#H3 and H6 (plus others subset as well) MMs - constrained design
model_bypol_full <- DV_support ~ Background + Prior3 + badbehavior1*country1 + Inaction + Author + Rationale + EffectOrd 

mms_bypol_full <- cj(combo, model_bypol_full, 
                     id = ~1, alpha=0.05, estimate = "mm", by = ~ Policy)

diff_mms_mms_bypol_full <- cj(combo, model_bypol_full,
                              id = ~1, alpha=0.05, estimate = "mm_diff", by = ~ Policy)


mms_bypol_full <- mms_bypol_full %>%
  mutate(feature = recode(feature, "badbehavior1" = "Issue", "Inaction" = "If no action", "Prior3" = "Prior attitude", 
                          "EffectOrd" = "Effect on target economy", "country1" = "Country"),
         level = recode(level, "terror" = "Terror", "drugs" = "Drugs", 
                        "developnukes" = "WMD", "stopdemocracy" = "Democracy crackdown",
                        "TickingClock" = "Ticking clock", "Continue" = "Continuation",
                        "Appointee_only" = "Appointee", "Appointee_donor" = "Appointee donor",
                        "Professional_expert" = "Professional expert"))

diff_mms_mms_bypol_full <- diff_mms_mms_bypol_full %>%
  mutate(feature = recode(feature, "badbehavior1" = "Issue", "Inaction" = "If no action", "Prior3" = "Prior attitude", 
                          "EffectOrd" = "Effect on target economy", "country1" = "Country"),
         level = recode(level, "terror" = "Terror", "drugs" = "Drugs", 
                        "developnukes" = "WMD", "stopdemocracy" = "Democracy crackdown",
                        "TickingClock" = "Ticking clock", "Continue" = "Continuation",
                        "Appointee_only" = "Appointee", "Appointee_donor" = "Appointee donor",
                        "Professional_expert" = "Professional expert"))

  plot(rbind(mms_bypol_full, diff_mms_mms_bypol_full)) + ggplot2::facet_wrap(~BY, ncol = 4L) + scale_color_jco() +
  labs(x="Marginal means") + theme(legend.position="none")

ggsave("Output/F5_appendix_full_version.pdf", # in appendix
       width = 6.5, height = 6, dpi = 300, units = "in", device='pdf')


amces_bypol_base <- amces_bypol_full %>%
  filter(feature != "Country" & feature != "Rationale" & feature != "Effect on target economy")


plot(rbind(amces_bypol_base)) + ggplot2::facet_wrap(~BY, ncol = 4L) + scale_colour_viridis_d( begin = 0, end = .7) +
  labs(x="Average marginal component effects") + theme(legend.position="none", axis.title = element_text(size = 8))

ggsave("Output/Figure4.pdf", # paper Figure 4 
       width = 6.5, height = 3.75, dpi = 300, units = "in")


mms_bypol_base <- mms_bypol_full %>%
  filter(feature != "Country" & feature != "Rationale" & feature != "Effect on target economy")

diff_mms_mms_bypol_base <- diff_mms_mms_bypol_full %>%
  filter(feature != "Country" & feature != "Rationale" & feature != "Effect on target economy")


plot(rbind(mms_bypol_base, diff_mms_mms_bypol_base)) + ggplot2::facet_wrap(~BY, ncol = 4L) + scale_colour_viridis_d( begin = 0, end = .7) +
  labs(x="Marginal means") + theme(legend.position="none", axis.title = element_text(size = 8))

ggsave("Output/Figure5.pdf", # paper Figure 5
       width = 6.5, height = 3.75, dpi = 300, units = "in")



#############################################################################
### Un-comment these lines if you want to replicate all appendix material ###
#############################################################################

# source("Code/Appendix.R")
# source("Code/Factor_analysis.R")

